﻿
using System.Collections;
using System.Collections.Generic;

namespace SimpleFramework
{
    public interface IIdxTable: IEnumerable
    {
        void Read(byte[] bytes);

        int Count { get; }
    }

    /// <summary>
    /// 表格对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IdxTable<T> : IEnumerable<KeyValuePair<int, T>>, IIdxTable where T : IIdxEntity, new()
    {
        protected Dictionary<int, T> m_EntityDict = new Dictionary<int, T>();
        protected int[] m_Keys = null;

        public T this[int key]
        {
            get
            {
                return Get(key);
            }
        }

        /// <summary>
        /// 解析二进制数据
        /// </summary>
        /// <param name="bytes"></param>
        public void Read(byte[] bytes)
        {
            try
            {
                m_EntityDict.Clear();
                var reader = new DataBufferReader(bytes);
                var count = reader.ReadInt32();
                m_Keys = new int[count];
                for (int i = 0; i < count; ++i)
                {
                    var node = new T();
                    node.Read(reader);
                    var key = node.GetKey();
                    m_EntityDict.Add(key, node);
                    m_Keys[i] = key;
                }
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError("解析失败=>" + typeof(T).FullName);
                UnityEngine.Debug.LogError(ex);
                //throw;
            }
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get(int key)
        {
            T result;
            if (m_EntityDict.TryGetValue(key, out result))
            {
                return result;
            }
            return default(T);
        }


        /// <summary>
        /// 获取实例(通过索引)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IIdxEntity GetByIndex(int index)
        {
            return Get(m_Keys[index]);
        }

        /// <summary>
        /// 数目
        /// </summary>
        /// <returns></returns>
        public int Count
        {
            get
            {
                return m_EntityDict.Count;
            }
        }

        public IEnumerator<KeyValuePair<int, T>> GetEnumerator()
        {
            return m_EntityDict.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return m_EntityDict.GetEnumerator();
        }
    }
}